package cn.itcast.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

import static cn.itcast.nio.c1.ByteBufferUtil.debugAll;

/**
 * @Author: LDeng
 * @Date: 2021-05-13 14:21
 */
@Slf4j
public class MultyThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        //1，创建固定数量的worker,
        Worker worker = new Worker("worker-0");
        // 初始化selector， 启动worker-0线程

        while(true){
            boss.select();
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}",sc.getRemoteAddress());
                    log.debug("before register...{}",sc.getRemoteAddress());
                    //2， 关联selector
                    worker.register(sc);


                    log.debug("after register...{}",sc.getRemoteAddress());
                }
            }

        }
    }


    static class Worker implements Runnable{
        private Thread thread;
        private Selector workerSelector;
        private String name;
        private volatile boolean start=false;//标记是否初始化过
        private ConcurrentLinkedQueue<Runnable> queue=new ConcurrentLinkedQueue<>();//两个线程间传递数据

        public Worker(String name) {
            this.name = name;
        }

        //初始化线程和Selector
        public void register(SocketChannel sc) throws IOException {
            if(!start) {
                workerSelector = Selector.open();
                thread = new Thread(this,name);
                thread.start();
                start=true;

            }
            //借助队列，让两个线程之间通信
            // 向队列添加任务，但任务并没有立刻执行， boss线程添加 ， worker-0线程取出执行，
            //确保是work-0线程执行的代码
            queue.add(()->{
                try {
                    sc.register(workerSelector,SelectionKey.OP_READ,null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            workerSelector.wakeup();//唤醒workerSelector

        }

        @Override
        public void run() {
            while(true){
                try {
                    workerSelector.select();// worker-0 阻塞， wakeup
                    Runnable task = queue.poll();
                    if(task!=null){
                        task.run(); //执行了sc.register(workerSelector,SelectionKey.OP_READ,null);注册
                    }
                    Iterator<SelectionKey> iterator = workerSelector.selectedKeys().iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isReadable()){
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel sc = (SocketChannel) key.channel();
                            log.debug("client readed data from sc...{}",sc.getRemoteAddress());
                            sc.read(buffer);
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
